<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并确认',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createPersonName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <OrderInfo :produceTaskBillNo="form.produceTaskBillCode" />
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="单据单号" prop="scrapBillNo">
              <ElInputBox :data="form" dataName="scrapBillNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="报废日期" prop="scrapBatchDate" isRules>
              <ElDayBox :data="form" dataName="scrapBatchDate" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="单据备注" prop="scrapRemark" class="wAuto">
              <ElInputBox :data="form" dataName="scrapRemark" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="红冲原因" prop="redStrikeRemark" class="wAuto" v-if="!!form.redStrikeRemark">
              <ElInputBox :data="form" dataName="redStrikeRemark" type="textarea" disabled />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop>
          <TableBoxMx :data="{
            disabled: !isEdit,
            tbody: form.scrapMxDataList,
            thead: [
              {
                label: '产品名称',
                prop: 'productName',
                align: 'left',
                width: 320,
              },
              {
                label: '产品型号',
                prop: 'productSpecificationName',
                align: 'left',
                width: 160,
              },
              {
                label: '版本',
                prop: 'productVersion',
                align: 'center',
                width: 60,
              },
              {
                label: '生产批次',
                prop: 'produceTaskBillNo',
                align: 'center',
                width: 120,
              },
              {
                label: '生产日期',
                prop: 'productionDate',
                align: 'center',
                width: 120,
              },
              {
                label: '库区库位',
                prop: 'wareHouseAreaSheltName',
                align: 'center',
                width: 160,
              },
              {
                label: '库存数量',
                prop: 'stockQuantity',
                align: 'center',
                width: 160,
                hidden: !isEdit,
              },
              {
                label: '报废数量',
                prop: 'scrapQuantity',
                align: 'center',
                width: 140,
                formType: 'number',
                formProp: 'scrapMxDataList',
              },
              {
                label: '备注',
                prop: 'scrapMxRemark',
                align: 'left',
                width: null,
                formType: 'text'
              },
            ],
            operation: [
              {
                label: '删除',
                icon: 'Delete',
              }
            ],
            add: () => {
              if (form.scrapBatchDate) {
                pupAdd.state = true
                getAddTbody()
              } else {
                proxy.$message('请先选择报废日期', 'error');
              }
            },
          }">
          </TableBoxMx>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
  <SelectCom :pup="pupAdd" :table="pupAdd.tableAdd" isCheckbox :selectable="(row: any) => {
    const _arr = data.form.scrapMxDataList.map((el: any) => el.productStockNo)
    return !_arr.includes(row.productStockNo)
  }" @searchBtn="getAddTbody" @selectBtn="(arr: any) => {
    const _arr = arr.map((el: any) => ({
      ...el,
      wareHouseAreaSheltName: el.warehouseInfo
    }))
    data.form.scrapMxDataList.push(..._arr)
  }">
  </SelectCom>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs.ts'; // 引入逻辑
const { dataInfo, options } = useListComponent();
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    scrapBillCode: '', // 成品报废单唯一code
    scrapBatchDate: '', // 报废批次日期
    scrapRemark: '', // 报废备注说明
    scrapMxDataList: []
  },
});
const isEdit = ref(true)
//获取成品信息
const getAddTbody = () => {
  const _table = pupAdd.tableAdd
  _table.loading = true
  proxy.$api.FinishedProduct.GetFinishedProductStockDetailPageList({
    ..._table.search,
    endProductionDate: data.form.scrapBatchDate,
  })
    .then((res: any) => {
      _table.tbody = res.list
      _table.search.totalCount = res.totalCount;
      _table.loading = false
    })
    .catch(() => {
      _table.loading = false
    });
}
const pupAdd: any = reactive({
  state: false,
  typeName: 0,
  title: `选择成品`,
  tbody: [],
  tableAdd: {
    rowKey: 'productStockNo',
    search: {
      pageIndex: 1, //当前页码
      pageSize: 30, //每页显示数据的数量
      totalCount: 0, //总数量
      queryDataBaseFiled: '', // 关键字查询字段，空值查询全部
      likeWords: '', // 查询关键字，空值查询全部
      onlySelf: 0, // 是否只查询自己创建的，0：查所有、1：只查自己创建的
      isShowDisabled: -1, // 是否显示禁用,-1：显示所有的；0：仅显示未作废的；1 仅显示作废的
      orderByFiled: '', // 排序字段
      orderByType: 1, // 排序方式，0-倒序,1-升序
      beginTime: '', // 生产日期范围-开始时间
      endTime: '', // 生产日期范围-结束时间
      //
      endProductionDate: '', //最后生产批次日期
      onlyStocked: 1//仅查看有库存，-1 查全部、0-仅查库存数量为0的、1-仅查库存数量大于0的
    },
    tbody: [],
    thead: [
      {
        label: '成品名称',
        prop: 'productName',
        align: 'left',
        width: null,
        isCanSearch: true
      },
      {
        label: '型号规格',
        prop: 'productSpecificationName',
        align: 'left',
        width: 220,
      },
      {
        label: '产品版本',
        prop: 'productVersion',
        align: 'center',
        width: 160,
      },
      {
        label: '客户名称',
        prop: 'customerName',
        align: 'center',
        width: 220,
        isCanSearch: true
      },
      {
        label: '协议书号',
        prop: 'xieYiShuHao',
        align: 'center',
        width: 160,
        isCanSearch: true
      },
      {
        label: '生产批次',
        prop: 'produceTaskBillNo',
        align: 'center',
        width: 160,
        isCanSearch: true
      },
      {
        label: '生产日期',
        prop: 'productionDate',
        align: 'center',
        width: 140,
      },
      {
        label: '库区库位',
        prop: 'warehouseInfo',
        align: 'center',
        width: 180,
      },
      {
        label: '库存数量',
        prop: 'stockQuantity',
        align: 'center',
        width: 140,
      },
    ],
  },
});
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
//获取数据
const getForm = async () => {
  const _query: any = route.query
  setLoading()
  //是否新建
  if (!!!_query.code) {
    data.loading = false
    return
  }
  proxy.$api.Warehouse.GetFinishedProductScrapBillDetail({
    code: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type)
      data.form = {
        ...res.baseData,
        scrapMxDataList: res.mxDataList,
      }
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const saveBtn = (form: any, isConfirm: boolean = false, isPartial?: number) => {
  const _form: any = {
    scrapBillCode: form.scrapBillCode, // 成品报废单唯一code
    scrapBatchDate: form.scrapBatchDate, // 报废批次日期
    scrapRemark: form.scrapRemark, // 报废备注说明
    scrapMxDataList: form.scrapMxDataList.map((el: any) => (
      {
        productStockNo: el.productStockNo, // 成品规格库存代码
        scrapQuantity: el.scrapQuantity, // 报废数量
        scrapMxRemark: el.scrapMxRemark, //报废备注说明
      }
    ))
  }
  // return
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.Warehouse.CreateNewFinishedProductScrapBill(_form)
        .then((res: any) => {
          if (isConfirm) {
            _setState(res)
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;
    case '2'://编辑
      proxy.$api.Warehouse.UpdateFinishedProductScrapBill(_form)
        .then((res: any) => {
          if (isConfirm) {
            _setState(_form)
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;
    default:
      break;
  }
  function _sun() {
    closeBtn('保存成功')
  }
  function _setState(row: any) {
    proxy.$api.Warehouse.SureFinishedProductScrapBill({
      code: row.scrapBillCode, //
    })
      .then((res: any) => {
        _sun()
      })
      .catch(() => {
        _sun()
      });
  }
};
const closeBtn = (message?: string) => {
  if (message) {
    proxy.$message(message)
  }
  sendMsg('save', true);
  // getForm()
  window.close();
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
onMounted(() => {
  getForm();
});
</script>
